package com.moneywelcome.antifraudassembly.apiimpl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moneywelcome.antifraudassembly.exceptions.NoSuchInfoException;
import com.moneywelcome.antifraudassembly.model.UserIdcard;
import com.moneywelcome.antifraudassembly.service.UserIdcardService;
import com.moneywelcome.antifraudfacade.api.UserIdcardApi;
import com.moneywelcome.antifraudfacade.form.IdcardForm;
import com.moneywelcome.antifraudfacade.info.IdcardInfo;
import com.moneywelcome.results.Result;
//import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class UserIdcardApiImpl implements UserIdcardApi {

    @Autowired
    private UserIdcardService idcardService;

    /**
     * 保存身份证信息
     * @param form
     * @return
     */
//    @GlobalTransactional
    @Override
    public Result saveIdcard(IdcardForm form) {
        log.info("新增身份证：{}",form);
        UserIdcard userIdcard = BeanUtil.copyProperties(form, UserIdcard.class);
        return idcardService.save(userIdcard)?Result.success():Result.fail();
    }

    /**
     * 用户id获取身份证信息
     * @param userId
     * @return
     */
    @Override
    public Result<IdcardInfo> getIdcard(Integer userId) {
        log.info("查询身份证信息userId：{}",userId);
        UserIdcard userIdcard = idcardService.getOne(new QueryWrapper<UserIdcard>().eq("user_id", userId));
        return null==userIdcard?Result.fail("没有该信息"):Result.success(BeanUtil.copyProperties(userIdcard, IdcardInfo.class));
    }

    /**
     * 修改身份证信息
     * @param form
     * @return
     */
//    @GlobalTransactional
    @Override
    public Result modifyIdcard(IdcardForm form) {
        log.info("修改身份证:{}",form);
        UserIdcard idcard = idcardService.getOne(new QueryWrapper<UserIdcard>().eq("user_id", form.getUserId()).eq("idcard_number", form.getIdcardNumber()));
        if (null==idcard) throw new NoSuchInfoException("找不到身份证","NO_SUCH_IDCARD");
        UserIdcard userIdcard = BeanUtil.copyProperties(form, UserIdcard.class);
        userIdcard.setUserIdcardId(idcard.getUserIdcardId());
        return idcardService.updateById(userIdcard)?Result.success():Result.fail("数据没有改变");
    }
}
